layui.define(['layer', 'jquery'], function (exports) {
    var layer = layui.layer
    var laypage = layui.laypage
    var $ = layui.$
    var upload = layui.upload

    var win = window.top
    if (window.top === window.self) {
        win = window.self
    }

    var popup = {
        // 消息
        msg: function (obj) {
            obj.code = obj.code || 3
            obj.title = obj.msg || "未知"
            obj.wait = obj.wait || 1
            obj.fun = obj.fun || function () {
                if (typeof obj.url !== "undefined" && obj.url != "" && obj.url != null) {
                    window.location.href = obj.url;
                } else {
                    window.location.reload()
                }
                win.layer.closeAll("loading")
            }
            win.layer.msg(obj.title, { icon: obj.code, time: obj.wait * 1000 }, obj.fun)
        },
        // 弹出iframe
        iframe: function (url) {
            win.layer.open({
                type: 2,
                shadeClose: true,
                maxmin: true, //开启最大化最小化按钮
                area: ['800px', '600px'],
                content: url,
            })
        },
        // 询问
        confirm: function (url, data, type = "DELETE", title = "确定操作吗？") {
            win.layer.confirm(title, { icon: 3 }, function () {
                $.ajax({
                    url: url,
                    data: data,
                    type: type,
                    success: function (result) {
                        popup.msg(result)
                    },
                    error: function (xhr, status, error) {
                        popup.msg({ code: 3, msg: "网络错误" })
                    }
                });
            });
        },
        // 弹出相册
        photos: function (obj, start = 0, title = "相册组") {
            win.layer.photos({
                photos: {
                    "title": title,
                    "start": start,
                    "data": obj
                }
            })
        },
        // 表验证弹出
        formValid: function (elem, msg, icons = 5) {
            var DANGER = 'layui-form-danger'; // 警示样式
            var formInput = $('.layui-form .' + DANGER)
            formInput.removeClass(DANGER); // 清除样式
            win.layer.msg(msg, { icon: icons, shift: 6 });
            elem.focus()
            elem.addClass(DANGER);
        },
        // 表单提交
        formSubmit: function (url = "", data = {}, fun = function () { }) {
            var loadIndex = win.layer.load();
            $.post(url, data, function (res) {

                if (res.code == 1) {
                    if (typeof $(window.top.document).find(`.layui-tab-content .layui-show iframe`)[0] !== 'undefined') {
                        var topDom = $(window.top.document).find(`.layui-tab-content .layui-show iframe`)[0].contentWindow;

                        if (typeof topDom.layui.table.cache.table !== 'undefined') {
                            topDom.layui.table.reload("table")
                        } else if (typeof topDom.layui.table.cache["treeTable"] !== 'undefined') {
                            topDom.layui.treeTable.reload("treeTable")
                        }
                    }
                    win.layer.msg(res.msg, { icon: res.code, time: 1000 }, function () {
                        win.layer.close(loadIndex)
                        if (res.url != "" && res.url != null) {
                            window.location.href = res.url;
                        } else {
                            window.location.reload()
                        }
                    })

                } else {
                    win.layer.close(loadIndex)
                    if (res.data && res.data.key) {
                        var othis = $(`.layui-form-item *[name="${res.data.key}"]`);
                        // console.log(othis);
                        popup.formValid(othis, res.data.msg)
                    } else {
                        win.layer.msg(res.msg, { icon: 5, shift: 6 });
                    }
                }
                fun()
            })
        },
        // 弹出附件组 attribute
        attachment: function (obj) {
            obj["num"] = obj["num"] || 1
            obj["title"] = obj["title"] || "附件管理"
            obj["attribute"] = obj["attribute"] || ""  //属性追加
            $(obj["elem"]).html(`
            <div class="attribute_box">
                <div class="layui-input-wrap">
                    <input type="text" class="layui-input" ${obj["attribute"]}>
                </div>
                <a href="javascript:;" class="layui-btn layui-btn-primary uploads">上传文件</a>
            </div>
            <div class="attribute_list">
            </div>
            `)
            $(`.attribute_box`).css({ "display": "flex", "flex-wrap": "nowrap" })
            $(obj["elem"]).find("input").on("keyup input", function () {
                var html = "";
                if ($(this).val() != "") {
                    var arr = $(this).val().split(",")
                    if (arr.length > obj["num"]) {
                        layer.msg("最大文件数为" + obj["num"])
                        $(this).val(arr.slice(0, obj["num"]).join(","))
                    }
                    $.each(arr, function (k, v) {
                        var imageExtensions = ["jpg", "jpeg", "png", "gif"];
                        var isImage = imageExtensions.some(function (extension) {
                            return v.toLowerCase().endsWith(extension);
                        });
                        if (isImage) {
                            html += `<div class="box">
                                <a href="javascript:;" data-src="${v}">
                                    <i class="layui-icon layui-icon-delete"></i>
                                </a>
                                <img src="${v}">
                            </div>`
                        } else {
                            html += `<div class="box">
                                <a href="javascript:;" data-src="${v}">
                                    <i class="layui-icon layui-icon-delete"></i>
                                </a>
                                <i class="layui-icon layui-icon-file" data-src="${v}"></i>
                            </div>`
                        }
                    })
                }
                $(obj["elem"]).find(".attribute_list").html(html)
            })
            $("body").delegate(`${obj["elem"]} .attribute_list .box>a`, "click", function () {
                var index = $(this).parent().index()
                var inputVal = $(obj["elem"]).find("input")
                var arr = inputVal.val().split(",")
                arr.splice(index, 1);
                inputVal.val(arr.join(","))
                inputVal.trigger('input');
            })
            $(obj["elem"]).find(".uploads").click(function () {
                var data = obj
                var unid = Math.random().toString(36).substring(2, 11)
                layer.open({
                    type: 1,
                    shadeClose: true,
                    maxmin: true, //开启最大化最小化按钮
                    area: ["100%", "100%"],
                    title: obj["title"],
                    content: `
                    <div id="${unid}" class="attribute_layer" style="padding:10px;">
                        <div class="layui-tab">
                            <ul class="layui-tab-title">
                                <li class="layui-this">文件上传</li>
                                <li>附件库存</li>
                            </ul>
                            <div class="layui-tab-content">
                                <div class="layui-tab-item layui-show">
                                    <a href="javascript:;" class="layui-btn ID-upload-demo-btn" data-unid="${unid}">点击上传</a>
                                </div>
                                <div class="layui-tab-item">
                                    <div class="layui-raw list layui-col-space5"></div>
                                    <div class="layui-raw">
                                        <div id="${unid}_page" class="layui-col-xs12"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    `,
                    success: function () {
                        // 分页
                        $.post(data.url, { page: 1, limit: 12 }, function (onces) {
                            laypage.render({
                                elem: `${unid}_page`,
                                limit: 12,
                                curr: 1, // 当前页
                                count: onces.total, // 数据总数，从后端得到
                                jump: function (obj, first) {
                                    var oneHtml = ""
                                    $.each(onces.data, function (k, v) {
                                        var imageExtensions = ["jpg", "jpeg", "png", "gif"];
                                        var isImage = imageExtensions.some(function (extension) {
                                            return v.url.toLowerCase().endsWith(extension);
                                        });
                                        var str = ""
                                        if (isImage) {
                                            str = `<img src="${v.url}">`
                                        } else {
                                            str = `<i class="layui-icon layui-icon-file" data-src="${v.url}"></i>`
                                        }
                                        oneHtml += `<div class="layui-col-xs3 ls"><div class="img" data-src="${v.url}">${str}</div><p>${v.name}</p></div>`
                                    })
                                    $(`#${unid} .list`).html(oneHtml)
                                    // var 
                                    // 首次不执行
                                    if (!first) {
                                        // do something
                                        $.post(data.url,
                                            { page: obj.curr, limit: obj.limit },
                                            function (res) {
                                                var htmls = ""
                                                $.each(res.data, function (kk, vv) {
                                                    var imageExtensions = ["jpg", "jpeg", "png", "gif"];
                                                    var isImage = imageExtensions.some(function (extension) {
                                                        return vv.url.toLowerCase().endsWith(extension);
                                                    });
                                                    if (isImage) {
                                                        vv.url = `<img src="${vv.url}">`
                                                    } else {
                                                        vv.url = `<i class="layui-icon layui-icon-file" data-src="${vv.url}"></i>`
                                                    }
                                                    htmls += `<div class="layui-col-xs3 ls"><div class="img">${vv.url}</div><p>${vv.name}</p></div>`
                                                })
                                                $(`#${unid} .list`).html(htmls)
                                            })
                                    }
                                }
                            });
                        })
                        // 上传 ID-upload-demo-btn
                        upload.render({
                            elem: `.ID-upload-demo-btn`,
                            url: obj.uploadUrl,
                            data: {
                                category: "无类别"
                            },
                            before: function () {
                                layer.load();
                                var inputVal = $(obj["elem"]).find("input")
                                if (inputVal.val() != "") {
                                    var arr = inputVal.val().split(",")
                                    if (arr.length >= obj["num"]) {
                                        layer.msg("最大文件数为" + obj["num"])
                                        inputVal.val(arr.slice(0, obj["num"]).join(","))
                                        inputVal.trigger('input');
                                        layer.closeAll('loading')
                                        layer.closeAll('page')
                                        return false;
                                    }
                                }
                            },
                            done: function (res) {
                                if (res.code == 1) {
                                    var inputVal = $(obj["elem"]).find("input")
                                    if (inputVal.val() != "" && inputVal.val() != "") {
                                        var arr = inputVal.val().split(",")
                                        if (arr.length < obj["num"]) {
                                            arr.push(res.url)
                                            inputVal.val(arr.join(","))
                                            inputVal.trigger('input');
                                        } else {
                                            layer.msg("最大文件数为" + obj["num"])
                                        }
                                    } else {
                                        inputVal.val(res.url)
                                        inputVal.trigger('input');
                                    }
                                } else {
                                    layer.msg(res.msg, { icon: res.code })
                                }
                                layer.closeAll('page')
                                layer.closeAll('loading')
                            },
                            error: function () {
                                layer.msg("上传失败，请检查网络")
                            }
                        })
                        // 文件选择
                        $("body").delegate(`#${unid} .list .ls .img`, "click", function () {
                            var src = $(this).attr("data-src");
                            var inputVal = $(obj["elem"]).find("input")
                            if (inputVal.val() != "") {
                                var arr = inputVal.val().split(",")
                                if (arr.length < obj["num"]) {
                                    arr.push(src)
                                    inputVal.val(arr.join(","))
                                    inputVal.trigger('input');
                                } else {
                                    layer.msg("最大文件数为" + obj["num"])
                                }
                            } else {
                                inputVal.val(src)
                                inputVal.trigger('input');
                            }
                            layer.closeAll('page')
                        })
                    }
                })
            })
            $(obj["elem"]).find("input").trigger('input');
        }
    }

    exports('popup', popup); // 输出模块
});  